import axios from 'axios'
import NProgress from 'nprogress'
import { ElNotification } from 'element-plus'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 300000,
  headers: {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': 'application/json',
  },
})

/**
 * 在 request 拦截器 TODO
 */
service.interceptors.request.use(
  config => {
    if (config.progress === undefined) {
      //不展示加载动画
      NProgress.start()
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

/**
 * response 拦截器 TODO
 */
service.interceptors.response.use(
  response => {
    NProgress.done()
    console.log('[ response.data ] >', response.data)
    if (response.data.errors) {
      ElNotification.error({
        message: response.data.errors[0].message,
        title: 'Error',
      })
      return Promise.reject(response.data.errors)
    } else {
      // 请求成功
      return Promise.resolve(response.data.data)
    }
  },
  error => {
    if (error.message === 'Request aborted') {
      return Promise.reject(error)
    }
    ElNotification.error({
      message: 'System under maintenance',
      title: 'Error',
    })
    return Promise.reject(error)
  }
)

export default service
